<template>
	<view class="page">
		<!-- 顶部统计区域 -->
		<view class="stats">
			<view class="stats-row">
				<view class="stats-col">
					<view class="num">{{ monthSummary.times }}</view>
					<view class="label">跑步次数</view>
				</view>
				<view class="stats-col center">
					<view class="num big">{{ monthSummary.steps }}</view>
					<view class="label">累计步数</view>
				</view>
				<view class="stats-col">
					<view class="num">{{ monthSummary.duration }}</view>
					<view class="label">总时长</view>
				</view>
			</view>

			<!-- 月份 Tabs（wot-design-uni） -->
			<view class="tabs-wrap">
				<wd-tabs v-model="activeMonth" swipeable sticky @change="onMonthChange" color="#2e7d32"
					inactive-color="#999999" lineWidth="40">
					<block v-for="m in months" :key="m.key">
						<wd-tab :name="m.key" :title="m.text">
							<wd-divider></wd-divider>
							<!-- 当前月摘要 -->
							<view class="month-brief">
								{{ currentMonthLabel }}　{{ monthSummary.steps }}步数　累计{{ monthSummary.times }}次　共{{ monthSummary.duration }}
							</view>


							<!-- 内容区域：跑步记录卡片（会随月份切换） -->
							<view class="content">
								<view class="record-list">
									<wd-card v-for="item in records" :key="item.id" class="record-card"
										:use-footer-slot="true">
										<!-- 头部：日期 / 时间 -->
										<template #title>
											<text class="date">{{ item.date }} / {{ item.time }}</text>
										</template>

										<!-- 主体 -->
										<template #default>
											<view class="card-body">
												<view class="row">
													<view class="col">
														<text class="label">步数：</text>
														<text class="val">{{ item.steps }}</text>
													</view>
													<view class="col">
														<text class="label">运动时长：</text>
														<text class="val">{{ item.duration }}</text>
													</view>
												</view>

												<view class="row">
													<view class="col">
														<text class="label">平均配速：</text>
														<text class="val">{{ item.pace }}</text>
													</view>

													<!-- 分享按钮（小程序） -->
													<!-- #ifdef MP-WEIXIN -->
													<button class="share" open-type="share" :data-id="item.id">
														<wd-icon name="share" size="18" />
														<text>分享</text>
													</button>
													<!-- #endif -->
												</view>
											</view>
										</template>
									</wd-card>

									<wd-divider v-if="loading">加载中...</wd-divider>
									<wd-divider v-else-if="!records.length">本月暂无记录</wd-divider>

								</view>
							</view>
						</wd-tab>
					</block>
				</wd-tabs>
			</view>
		</view>
	</view>
</template>
<script setup>
	import {
		ref,
		computed,
		watch,
		onMounted
	} from 'vue'
	import {
		useAppStore
	} from '@/stores/app'

	const store = useAppStore()

	/* ====== 顶部统计（总汇总，保持不变） ====== */
	// const summary = computed(() => store.runSummary)

	/* ====== 工具：时间处理（保持不变） ====== */
	function parseDurationToSeconds(str) {
		if (!str) return 0
		const normalized = String(str).replace(/：/g, ':').replace(/[^\d:]/g, '')
		const [hh = '0', mm = '0', ss = '0'] = normalized.split(':')
		return (+hh) * 3600 + (+mm) * 60 + (+ss)
	}

	function secondsToHHMMSS(total) {
		const h = Math.floor(total / 3600)
		const m = Math.floor((total % 3600) / 60)
		const s = total % 60
		const pad = (n) => String(n).padStart(2, '0')
		return `${pad(h)}:${pad(m)}:${pad(s)}`
	}

	function ts(rec) {
		const d = String(rec.date || '').replace(/-/g, '/')
		const t = rec.time || '00:00'
		return new Date(`${d} ${t}`).getTime()
	}

	/* ====== 关键改造点：Tabs 月份不再来自 store，而是“最近 N 个月” ====== */
	const MONTHS_WINDOW = 5 // 最近 5 个月：会生成 05→06→07→08→09 这类
	function monthKeyOf(date) {
		const y = date.getFullYear()
		const m = String(date.getMonth() + 1).padStart(2, '0')
		return `${y}-${m}`
	}

	function genRecentMonths(endKey = monthKeyOf(new Date()), count = MONTHS_WINDOW) {
		// 以 endKey 结尾，往前推 count-1 个月，返回“升序”数组
		const [ey, em] = endKey.split('-').map(Number)
		const endDate = new Date(ey, em - 1, 1)
		const arr = []
		for (let i = count - 1; i >= 0; i--) {
			const d = new Date(endDate.getFullYear(), endDate.getMonth() - i, 1)
			arr.push(monthKeyOf(d))
		}
		return arr
	}

	// 默认希望显示 2025-09（如果你想随当前时间自动变，用：monthKeyOf(new Date())）
	const DEFAULT_MONTH_KEY = monthKeyOf(new Date())

	// 生成 tabs 月份：升序
	const months = computed(() => {
		const keys = genRecentMonths(DEFAULT_MONTH_KEY, MONTHS_WINDOW) // 比如 ['2025-05','06','07','08','09']
		return keys.map(k => ({
			key: k,
			text: `${Number(k.slice(5))}月`
		}))
	})

	// 当前激活月份：默认 2025-09；若 tabs 不含这个 key，则回退到最后一个
	const activeMonth = ref(DEFAULT_MONTH_KEY)
	watch(
		months,
		(arr) => {
			if (!arr.length) return
			if (!arr.some(m => m.key === activeMonth.value)) {
				activeMonth.value = arr[arr.length - 1].key // 回退到最后一个（最新）
			}
		}, {
			immediate: true
		}
	)

	/* ====== 拉取数据：进入页/切换时都请求该月 ====== */
	const loading = computed(() => !!store.run.loadingByMonth?.[activeMonth.value])

	// 监听 activeMonth 变化时拉取；首屏也会触发
	watch(
		activeMonth,
		(key) => {
			if (key) store.fetchRunByMonth(key)
		}, {
			immediate: true
		}
	)

	// 兼容 tabs 的 change 事件
	function onMonthChange(e) {
		let key = ''
		if (typeof e === 'string' || typeof e === 'number') key = String(e)
		else if (e && typeof e === 'object') key = e.detail?.name ?? e.detail?.value ?? e.value ?? ''
		if (!key) key = activeMonth.value
		activeMonth.value = key
	}

	/* ====== 当前月记录 / 摘要（从 store 读取；空也能渲染“暂无记录”） ====== */
	const records = computed(() => {
		const list = store.run?.recordsByMonth?.[activeMonth.value] || []
		return list.slice().sort((a, b) => ts(b) - ts(a))
	})
	const currentMonthLabel = computed(
		() => months.value.find(v => v.key === activeMonth.value)?.text || ''
	)
	const monthSummary = computed(() => {
		const list = records.value
		const times = list.length
		const steps = list.reduce((s, r) => s + (r.steps || 0), 0)
		const totalSeconds = list.reduce((s, r) => s + parseDurationToSeconds(r.duration), 0)
		return {
			times,
			steps,
			duration: secondsToHHMMSS(totalSeconds)
		}
	})
</script>


<style scoped>
	/* 页面背景：顶部淡绿色渐变 → 下方纯白 */
	.page {
		min-height: 100vh;
		/* 绿色 -> 灰色，到 35% 结束渐变，下面纯灰 */
		background: linear-gradient(to bottom, #c4ffd5 0%, #f5f5f5 35%, #f5f5f5 100%);
	}

	/* 顶部统计区域 */
	.stats {
		padding: 60rpx 30rpx 20rpx;
	}

	.stats-row {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
	}

	.stats-col {
		flex: 1;
		text-align: center;
	}

	.stats-col.center {
		flex: 1.5;
	}

	.num {
		font-size: 36rpx;
		font-weight: 600;
		color: #000;
		line-height: 1.2;
	}

	.num.big {
		font-size: 56rpx;
		font-weight: 700;
	}

	.label {
		margin-top: 10rpx;
		font-size: 24rpx;
		color: #333;
	}

	/* Tabs 容器透明 + 左右边距相等（保持你的设置） */
	.tabs-wrap {
		margin-top: 30rpx;
		background-color: transparent;
		margin-left: -30rpx;
	}

	/* 覆盖 wot-tabs 默认白色背景和左右 padding */
	:deep(.wd-tabs),
	:deep(.wd-tabs__wrap),
	:deep(.wd-tabs__scroll),
	:deep(.wd-tabs__nav),
	:deep(.wd-tabs__nav--line),
	:deep(.wd-tabs__scroll-view),
	:deep(.wd-tabs__scroll-inner) {
		background: transparent !important;
		padding-left: 0 !important;
		padding-right: 0 !important;
		margin-left: 0 !important;
		margin-right: 0 !important;
		box-sizing: border-box;
	}

	/* 吸顶时也保持透明 */
	:deep(.wd-tabs--sticky) {
		background: transparent !important;
	}

	/* tab 文字颜色 */
	:deep(.wd-tabs__item) {
		color: #999;
	}

	:deep(.wd-tabs__item.is-active) {
		color: #2e7d32 !important;
	}

	/* 激活下划线 */
	:deep(.wd-tabs__line) {
		background-color: #2e7d32 !important;
		height: 6rpx !important;
		border-radius: 6rpx;
	}

	/* 当前月摘要和内容 */
	.month-brief {
		margin: 30rpx 80rpx 0;
		color: #333;
		font-size: 26rpx;
	}

	.content {
		padding: 24rpx 30rpx 60rpx;
	}

	/* 记录列表与卡片（wd-card） */
	.record-list {
		padding: 20rpx 0 40rpx;
	}

	.record-card {
		border: 2rpx solid #1f1f1f;
		border-radius: 24rpx;
		overflow: hidden;
		margin-bottom: 24rpx;
		box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, .06);
	}

	:deep(.wd-card__header) {
		padding: 20rpx 22rpx;
	}

	:deep(.wd-card__body) {
		padding: 0 22rpx 12rpx;
	}

	.date {
		color: #333;
		font-size: 28rpx;
		font-weight: 600;
	}

	.card-body {
		margin-top: 8rpx;
	}

	.row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 14rpx 2rpx;
		gap: 12rpx;
	}

	.col {
		display: flex;
		align-items: baseline;
		gap: 8rpx;
		min-width: 0;
	}

	.label {
		color: #666;
		font-size: 26rpx;
	}

	.val {
		color: #222;
		font-size: 28rpx;
		letter-spacing: 1rpx;
	}

	.share {
		display: inline-flex;
		align-items: center;
		gap: 8rpx;
		padding: 8rpx 16rpx;
		border-radius: 999rpx;
		border: 2rpx solid #cfcfcf;
		background: #fff;
		color: #444;
		line-height: 1;
		margin-left: 180rpx;
	}

	.share:active {
		background: #f5f5f5;
	}
</style>